package com.imooc.mybatisplusappdemo.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imooc.mybatisplusappdemo.dto.LoginDto;
import com.imooc.mybatisplusappdemo.entity.Account;
import com.imooc.mybatisplusappdemo.dao.AccountMapper;
import com.imooc.mybatisplusappdemo.entity.Resource;
import com.imooc.mybatisplusappdemo.service.AccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;


/**
 * <p>
 * 账号表 服务实现类
 * </p>
 *
 * @author sanchongmen
 * @since 2021-03-22
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements
    AccountService {

  @Override
  public LoginDto login(String username, String password) {
    LoginDto loginDto = new LoginDto();
    loginDto.setPath("redirect:/");

    Account account = lambdaQuery().eq(Account::getUsername, username).one();
    if (null == account) {
      loginDto.setError("用户名不能为空!");
      return loginDto;
    }

    MD5 md5 = new MD5(account.getSalt().getBytes());
    String digestHex = md5.digestHex(password);

    if (!digestHex.equals(account.getPassword())) {
      loginDto.setError("用户密码不正确!");
      return loginDto;
    }

    loginDto.setPath("login/main");
    loginDto.setAccount(account);
    return loginDto;

  }

  @Override
  public IPage<Account> accountPage(Page<Account> page, Wrapper<Account> wrapper) {
    return baseMapper.accountPage(page, wrapper);
  }

  @Override
  public Account getAccountById(long id) {
    return baseMapper.selectAccountById(id);
  }
}
